package cascade.controller.pages.commands
{
	import cascade.App;
	import cascade.model.Page;
	
	import flight.commands.AsyncCommand;
	import flight.net.RemoteService;
	
	import mx.rpc.Fault;

	public class CommandDeletePage extends AsyncCommand
	{
		
		protected var page:Page;
		
		public function CommandDeletePage(page:Page)
		{
			this.page = page;
		}
		
		public override function execute():*
		{
			Cascade.busy.addBusy(this);
			Cascade.service.SiteService.deletePage(page.id, result, fault);
		}
		
		protected function result(value:Object):void {
			var depth:uint = page.depth;
			var i:Number = Cascade.model.pages.getItemIndex(page);
			for (i; i < Cascade.model.pages.length; i) {
				if (Cascade.model.pages[i].vo.depth >= depth)
					break;
				Cascade.model.pages.removeItemAt(i);
			}
			
			// remove the page from the model siteTree
			if (page.parent) {
				page.parent.children.removeItemAt(page.parent.children.getItemIndex(page));
				if (page.parent.children.length == 0)
					page.parent.children = null;
			} else {
				Cascade.model.siteTree.removeItemAt(Cascade.model.siteTree.getItemIndex(page));
			}
			
			Cascade.busy.removeBusy(this);
			
			dispatchExecutionComplete();
		}
		
		protected function fault(info:Object):void {
			trace(info);
			
			Cascade.busy.removeBusy(this);
		}
	}
}
